﻿using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using NuPattern;
using NuPattern.Diagnostics;
using NuPattern.Runtime;

namespace SearchFormToolkit.Automation.ValueProviders
{
    /// <summary>
    /// A custom value provider that provides a value to other automation classes.
    /// </summary>
    [DisplayName("Search Form ViewModel")]
    [Category("MVC Search Form")]
    [Description("Gets the current value of the ViewModel for the search form, and returns the formatted value.")]
    [CLSCompliant(false)]
    public class SearchFormViewModelProvider : ValueProvider
    {
        private static readonly ITracer tracer = Tracer.Get<SearchFormViewModelProvider>();
        private const string DefaultFormatter = "{0}";

        /// <summary>
        /// Creates a new instance of the <see cref="SearchFormViewModelProvider"/> class;
        /// </summary>
        public SearchFormViewModelProvider()
        {
            this.Formatter = DefaultFormatter;
        }

        /// <summary>
        /// Gets or sets the formatter for this value.
        /// </summary>
        [DisplayName("Formatter")]
        [Description("The formatter to format the returned value.")]
        [DefaultValue(DefaultFormatter)]
        public string Formatter
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the current element.
        /// </summary>
        [Required]
        [Import(AllowDefault = true)]
        public ISearchForm CurrentElement
        {
            get;
            set;
        }

        /// <summary>
        /// Returns the provided result.
        /// </summary>
        /// <remarks></remarks>
        public override object Evaluate()
        {
            // Verify all [Required] and [Import]ed properties have valid values.
            this.ValidateObject();

            tracer.Info(
                "Evaluating ViewModel for current element '{0}' with Formatter '{1}'", this.CurrentElement.InstanceName, this.Formatter);

            var result = this.CurrentElement.DefaultView.SearchProvider.ViewModel;
            if (!string.IsNullOrEmpty(result)
                && !string.IsNullOrEmpty(this.Formatter))
            {
                // Format the result
                return string.Format(CultureInfo.CurrentCulture, this.Formatter, result);
            }

            tracer.Info(
                "Evaluated ViewModel for current element '{0}' with Formatter '{1}', as '{2}'", this.CurrentElement.InstanceName, this.Formatter, result);

            return result;
        }
    }
}
